<template>
    <!-- 对话框表单 -->
    <el-dialog
        class="ba-operate-dialog"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        :model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
        @close="baTable.toggleForm"
        :style="{ height: '90vh',top:'-10vh !important'}"
    >
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>
        <el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar" style="height:78vh">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '' : 'width: calc(100% - ' + baTable.form.labelWidth! / 8 + 'px)'"
            >
                <el-form
                    ref="formRef"
                    @keyup.enter="baTable.onSubmit(formRef)"
                    :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                    v-if="!baTable.form.loading"
                >   
                
                <el-card style="width:97%;margin-left: 3%;">
                    <template #header>
                        <div class="card-header">
                            <h4>基本信息</h4>
                        </div>
                    </template>
                    <FormItem
                        label="商品类型"
                        v-model="baTable.form.items!.pro_type"
                        type="radio"
                        :data="{
                            content: { 0: '普通商品', 1: '虚拟商品', 2: '卡密/网盘' },
                            childrenAttr: { border: true },
                        }"
                    />
                    <FormItem label="所属分类" type="remoteSelect" v-model="baTable.form.items!.cat_id" prop="cat_id" :input-attr="{ pk: 'cat.id', field: 'name', 'remote-url': '/admin/goods.GoodsCat/goodscatList' }"/>

                    <el-form-item prop="title" label="标题">
                        <el-input v-model="baTable.form.items!.title" type="string"></el-input>
                    </el-form-item>
                    <el-form-item prop="des" label="简介">
                        <el-input v-model="baTable.form.items!.des" type="string"></el-input>
                    </el-form-item>
                    <FormItem label="封面图" type="image" v-model="baTable.form.items!.feng" />
                    <el-form-item prop="unit" label="单位">
                        <el-input v-model="baTable.form.items!.unit" type="string"></el-input>
                    </el-form-item>
                    <FormItem label="上架" type="switch" v-model="baTable.form.items!.status" prop="status" />
                    <FormItem label="置顶" type="switch" v-model="baTable.form.items!.is_top" prop="is_top" />
                </el-card>

                <el-card style="width:97%;margin-left: 3%;margin-top: 15px;">
                    <template #header>
                        <div class="card-header">
                            <h4>规格库存</h4>
                        </div>
                    </template>
                    <FormItem
                        label="商品规格"  
                        v-model="baTable.form.items!.specs"
                        type="radio"
                        :data="{
                            content: { 0: '单规格', 1: '多规格'},
                            childrenAttr: { border: true },
                        }"
                    />
                    <block v-if="baTable.form.items!.specs == 0">
                        <el-form-item prop="price" label="售价">
                            <el-input v-model="baTable.form.items!.price" type="string"></el-input>
                        </el-form-item>
                        <el-form-item prop="origin_price" label="原价">
                            <el-input v-model="baTable.form.items!.origin_price" type="string"></el-input>
                        </el-form-item>
                        <el-form-item prop="stock" label="库存">
                            <el-input v-model="baTable.form.items!.stock" type="string"></el-input>
                        </el-form-item>
                        <el-form-item prop="pro_code" label="编号">
                            <el-input v-model="baTable.form.items!.pro_code" type="string"></el-input>
                        </el-form-item>
                    </block>
                    <block v-if="baTable.form.items!.specs == 1">
                    <el-form-item prop="guige" label="多规格设置">
                           <p style="margin-bottom: 15px">
                             <el-input v-model="pi.price" type="number" style="display: inline-block;width: 150px;" placeholder="价格"/>  <el-input type="number" style="display: inline-block;width: 150px;" placeholder="原价" v-model="pi.old_price"/> <el-input type="number" style="display: inline-block;width: 150px;" placeholder="库存" v-model="pi.stock"/> <el-button type="primary" style="display: inline-block;width: 100px;" @click="pi_set">批量设置</el-button> 
                           </p>
                           <table class="table table2">
                             <tr><td width="30%">规格名称</td><td width="12%">价格</td><td width="12%">原价</td><td width="10%">库存</td><td width="15%">排序</td><td width="100">操作</td></tr>
                             <tr v-for="(item,index) in guige">
                                <td><el-input v-model="item.name" placeholder="必填"/></td>
                                <td><el-input v-model="item.price" placeholder="必填"/></td>
                                <td><el-input v-model="item.origin_price" placeholder=""/></td>
                                <td><el-input-number v-model="item.stock"/></td>
                                <td><el-input v-model="item.sort" placeholder="数字越大越靠前"/></td>
                                <td><el-link :underline="false" type="danger" v-if="index>0" @click="del_guige(index)">移除</el-link> <span v-if="index==0">--</span></td>
                             </tr>
                             <tr>
                                <td colspan="5" style="text-align: left;">
                                     <el-button size="small" @click="add_guige">继续添加</el-button>
                                </td>
                             </tr>
                           </table>
                    </el-form-item>
                    </block>
                </el-card>


                <el-card style="width:97%;margin-left: 3%;margin-top: 15px;">
                    <template #header>
                        <div class="card-header">
                            <h4>商品详情</h4>
                        </div>
                    </template>
                     
                    <FormItem label="详情" type="editor" v-model="baTable.form.items!.content" />
                    
                </el-card>

                <el-card style="width:97%;margin-left: 3%;margin-top: 15px;margin-bottom: 50px;">
                    <template #header>
                        <div class="card-header">
                            <h4>物流设置</h4>
                        </div>
                    </template>
                     
                    <FormItem
                        label="物流方式"
                        v-model="baTable.form.items!.logistics"
                        type="radio"
                        :data="{
                            content: { 0: '快递', 1: '到店核销'},
                            childrenAttr: { border: true },
                        }"
                    />
                    <FormItem
                        label="运费设置"
                        v-model="baTable.form.items!.freight_type"
                        type="radio"
                        :data="{
                            content: { 0: '固定运费', 1: '运费模板',2:'包邮'},
                            childrenAttr: { border: true },
                        }"
                    />
                    <el-form-item prop="freight_price" label="固定运费" v-if="baTable.form.items!.freight_type == 0">
                        <el-input v-model="baTable.form.items!.freight_price" type="number" style="width:240px"></el-input>
                    </el-form-item>
                    <FormItem v-if="baTable.form.items!.freight_type == 1" label="运费模板" type="remoteSelect" v-model="baTable.form.items!.freight_tpl"
                        prop="freight_tpl"
                        :input-attr="{ pk: 'id', field: 'template_name', 'remote-url': '/admin/goods.FreightTeplate/getList' }"  placeholder="请选择运费模板"/>
                </el-card>
                
                </el-form>
            </div>
        </el-scrollbar>
        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm('')">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" @click="baTable.onSubmit(formRef)" type="primary">
                    {{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, inject, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import type baTableClass from '/@/utils/baTable'
import { regularPassword } from '/@/utils/validate'
import type { FormInstance, FormItemRule } from 'element-plus'
import FormItem from '/@/components/formItem/index.vue'
import router from '/@/router/index'
import { buildValidatorData } from '/@/utils/validate'
import { useConfig } from '/@/stores/config'
import createAxios from "/@/utils/axios";

const config = useConfig()
const formRef = ref<FormInstance>()
const baTable = inject('baTable') as baTableClass
const guige = ref([{'name':'','price':'','origin_price':'','stock':'999','sort':'','pic':''}])
const { t } = useI18n()
const pi = ref({'price':'','old_price':'','stock':''})
const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    title: [buildValidatorData({ name: 'required', title: '标题' })],
    nickname: [buildValidatorData({ name: 'required', title: t('user.user.nickname') })],
    group_id: [buildValidatorData({ name: 'required', message: t('Please select field', { field: t('user.user.grouping') }) })],
    email: [buildValidatorData({ name: 'email', title: t('user.user.email') })],
    mobile: [buildValidatorData({ name: 'mobile' })],
    password: [
        {
            validator: (rule: any, val: string, callback: Function) => {
                if (baTable.form.operate == 'Add') {
                    if (!val) {
                        return callback(new Error(t('Please input field', { field: t('user.user.password') })))
                    }
                } else {
                    if (!val) {
                        return callback()
                    }
                }
                if (!regularPassword(val)) {
                    return callback(new Error(t('validate.Please enter the correct password')))
                }
                return callback()
            },
            trigger: 'blur',
        },
    ],
})

const add_guige = () => {
    guige.value.push({'name':'','price':'','origin_price':'','stock':'999','sort':'','pic':''})
}
const del_guige_api = (id) =>{
    return createAxios({
        url: '/admin/goods.Goods/delSpecs',
        method: 'get',
        params:{"id":id}
    }).then(res => {

    })
}
const pi_set = () => {
      var arr = guige.value
      for(var i=0;i<arr.length;i++){
          arr[i].price = pi.value.price
          arr[i].origin_price = pi.value.old_price
          arr[i].stock = pi.value.stock
      }  
      guige.value = arr
}
const del_guige = (dex) => {
    if(dex == 0) return
    if(guige.value[dex].id != null && guige.value[dex].id > 0){
           del_guige_api(guige.value[dex].id)
    } 
    guige.value.splice(dex,1)
}
watch(
    () => [baTable.form.operate , guige.value],
    ([newVal,newVal2]) => {
        if(newVal == 'Edit' && baTable.form.items!.specs == 1){
            setTimeout(function(){
                guige.value = baTable.form.items!.guige
           },1000)
        }
        rules.password![0].required = newVal == 'Add'
        baTable.form.items!.guige = guige.value;
    }
)
</script>

<style>
.table2 .el-input__inner{
     text-align: center;
}
</style>
<style scoped lang="scss">
.table{
    border:1px solid #eee;
    border-collapse: collapse;
}
.table td{
    padding: 4px;border:1px solid #eee;
    text-align: center;
}
h4{
    margin: 0;
}
</style>
